<template>
  <div class="addVisiting-container">
    <!--		<div class="addVisiting-save">-->
    <!--			<van-button type="primary" size="small">保 存</van-button>-->
    <!--		</div>-->
    <van-form label-align="left" @submit="onSubmit('DCL')" ref="addQuoteForm">
      <van-cell-group inset>
        <van-field
          v-model="relevanceClue.sn"
          is-link
          readonly
          name="picker"
          label="关联商机"
          placeholder="点击选择关联商机"
          required
          :disabled="!!businessQuoteId"
          :rules="[{ required: true, message: '请选择关联商机' }]"
          @click="!businessQuoteId ? (showCluePicker = true) : ''"
        />
        <van-popup v-model:show="showCluePicker" position="bottom">
          <van-picker
            :columns="clueColumns"
            :columns-field-names="customFieldName"
            @confirm="onConfirmClue"
            @cancel="showCluePicker = false"
          />
        </van-popup>

        <van-field v-model="quoteTitle" name="报价单标题" label="报价单标题" placeholder="报价单标题" />
        <van-field
          v-model="quoteDate"
          is-link
          readonly
          name="datePicker"
          label="报价日期"
          @click="showQuoteDatePicker = true"
        />
        <van-popup v-model:show="showQuoteDatePicker" position="bottom">
          <van-datetime-picker type="datetime" @confirm="onConfirmQuoteDate" @cancel="showQuoteDatePicker = false" />
        </van-popup>
        <van-field
          v-model="quoteSubject.name"
          name="报价方"
          label="报价方"
          is-link
          required
          placeholder="报价方"
          :rules="[{ required: true, message: '请选择报价方' }]"
          @click="showQuoteSubjectPicker = true"
        />
        <van-popup v-model:show="showQuoteSubjectPicker" position="bottom">
          <van-picker
            :columns="quoteSubjectColumns"
            :columns-field-names="customQuoteName"
            @confirm="onConfirmQuoteSubject"
            @cancel="showQuoteSubjectPicker = false"
          />
        </van-popup>

        <van-field v-model="linkman" name="联系人" label="联系人" placeholder="请填写联系人" />
        <van-field v-model="linkmanPhone" name="手机号码" label="手机号码" placeholder="请填写手机号码" />
        <van-field v-model="linkmanEmail" name="邮箱" label="邮箱" placeholder="请填写邮箱" />
        <van-field v-model="inquirer" name="询价方" label="询价方" placeholder="请填写询价方" />
        <van-field
          v-model="inquirerLinkman"
          name="询价方联系人"
          label="询价方联系人"
          placeholder="请填写询价方联系人"
        />
        <van-field
          v-model="inquirerLinkmanPhone"
          type="number"
          name="询价方电话"
          label="询价方电话"
          placeholder="请填写询价方电话"
        />
        <van-field v-model="inquirerLinkmanEmail" name="询价方邮箱" label="询价方邮箱" placeholder="请填写询价方邮箱" />
        <div v-for="(item, index) in productItems" :key="item.id">
          <van-collapse v-model="activeName">
            <van-collapse-item :title="'产品明细' + (index + 1)" :name="index">
              <van-field
                v-model="item.name"
                is-link
                readonly
                name="picker"
                label="机型"
                placeholder="点击选择机型"
                @click="chooseBusinessModal(index)"
              />
              <van-popup v-model:show="showBusinessModalPicker" position="bottom" style="max-height: 580px">
                <van-search
                  v-model="businessSearchkey"
                  show-action
                  placeholder="请输入搜索关键词"
                  clear-trigger="always"
                  @search="onSearch"
                  @clear="onSearch"
                >
                  <template #action>
                    <div @click="onSearch">搜索</div>
                  </template>
                </van-search>
                <van-radio-group v-model="businiessProductId" @change="onConfirmBusinessModal">
                  <van-cell-group>
                    <van-cell
                      v-for="(item, index) in businessModalColumns"
                      :key="index"
                      :title="item.name"
                      clickable
                      @click="businiessProductId = item.id"
                    >
                      <template #right-icon>
                        <van-radio :name="item.id" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
                <van-empty v-if="!businessModalColumns.length" image-size="100" description="暂无机型" />
                <!-- <van-picker
                  :columns="businessModalColumns"
                  :columns-field-names="customBusinessModalName"
                  @confirm="onConfirmBusinessModal"
                  @cancel="showBusinessModalPicker = false"
                /> -->
              </van-popup>

              <van-field name="商业封面" label="商业封面">
                <template #input>
                  <van-uploader v-model="item.coverImageList" disabled readonly :max-count="1" :deletable="false" :preview-options="{closeable:'true'}" />
                </template>
              </van-field>
              <van-field
                v-model="item.fitMachine"
                type="textarea"
                rows="5"
                name="配置参数"
                label="配置参数"
                placeholder="配置参数"
              />
              <van-field v-model="item.isNewProduct" name="成色" label="成色" placeholder="请填写成色" disabled />
              <van-field v-model="item.price" name="月租" label="月租(元/月)" placeholder="请填写月租" />
              <van-field
                v-model="item.quantity"
                name="数量"
                type="number"
                label="数量"
                placeholder="请填写数量"
                @input="inputQuantity(item, index)"
              />
              <van-field v-model="item.amount" name="小计" label="小计(元/月)" placeholder="请填写小计" disabled />
              <van-field
                v-model="item.blackFreeQuantity"
                name="黑白免印量"
                type="number"
                label="黑白免印量"
                placeholder="请填写黑白免印量"
              />
              <van-field
                v-model="item.blackAdvancePrice"
                name="黑白超涨价"
                type="number"
                label="黑白超涨价"
                placeholder="请填写黑白超涨价"
              />
              <van-field
                v-model="item.colorFreeQuantity"
                name="彩色免印量"
                type="number"
                label="彩色免印量"
                placeholder="请填写彩色免印量"
              />
              <van-field
                v-model="item.colorAdvancePrice"
                name="彩色超涨价"
                type="number"
                label="彩色超涨价"
                placeholder="请填写彩色超涨价"
              />
              <van-field v-model="item.remark" type="textarea" name="备注" label="备注" placeholder="备注" />
            </van-collapse-item>
          </van-collapse>
          <div style="display: flex; align-items: center; justify-content: flex-end; margin: 20px 0 10px 0">
            <div style="display: flex">
              <div
                v-if="index + 1 === productItems.length"
                style="margin: 0 10px; font-size: 14px; color: #1989fa"
                @click="handleAddProduct(index)"
              >
                新增
              </div>
              <div
                v-if="productItems.length > 1"
                style="margin: 0 10px; font-size: 14px; color: #ff0000"
                @click="handleDeleteProduct(index)"
              >
                删除
              </div>
            </div>
          </div>
        </div>
        <van-field name="uploader" label="文件上传">
          <template #input>
            <van-uploader v-model="quoteFile" :after-read="afterRead" capture="camera"  :preview-options="{closeable:'true'}" />
          </template>
        </van-field>
        <van-field v-model="remark" type="textarea" name="备注" :label="'备注'" placeholder="备注" />
      </van-cell-group>
      <div class="bottom-operation">
        <!--				<van-button round block type="primary">-->
        <!--					新增商品-->
        <!--				</van-button>-->
        <van-button round block type="primary" style="margin: 0 20px" @click="onSubmit('DCL')"> 保存 </van-button>
        <van-button round block type="primary" style="margin: 0 20px" @click="onSubmit('YBJ')"> 保存并发送 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { formatter, formatterDate, formatterDateHourMinute } from '@/utils/index.js'
import {
  getQuoteSubject,
  getProductList,
  addBusinessQuotation,
  getBusinessDetail,
  getRelevanceClue
} from '@/api/businessOpportunity.js'
import request from '@/utils/request.js'
import { Toast } from 'vant'
import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
    const addQuoteForm = ref(null)
    const state = reactive({
      userInfo: {},
      businessQuoteId: '',
      relevanceClue: {},
      showCluePicker: false,
      clueColumns: [],
      customFieldName: { text: 'sn', value: 'id' },
      quoteTitle: '',
      quoteDate: '',
      showQuoteDatePicker: false,
      quoteSubject: {},
      showQuoteSubjectPicker: false,
      quoteSubjectColumns: [],
      customQuoteName: { text: 'name', value: 'id' },
      linkman: '',
      linkmanPhone: '',
      linkmanEmail: '',
      inquirer: '',
      inquirerLinkman: '',
      inquirerLinkmanPhone: '',
      inquirerLinkmanEmail: '',
      productItems: [
        {
          productName: '', //产品名称
          productSn: '', //产品sn
          productId: '', //产品id
          categoryId: '',
          categoryName: '',
          coverImageList: [], //产品封面
          fitMachine: '', //产品配置参数
          isNewProduct: '', //产品成色
          price: '', //产品月租
          quantity: '', // 产品数量
          amount: '', //产品小计
          blackFreeQuantity: '', //产品黑白免印数
          blackAdvancePrice: '', //产品黑白超张价
          colorFreeQuantity: '', //产品彩色免印量
          colorAdvancePrice: '', //产品彩色超张价
          remark: ''
        }
      ],
      businiessProductId:'',
      showBusinessModalPicker: false,
      chooseModalCurrent: 0,
      businessSearchkey: '',
      businessModalColumns: [],
      customBusinessModalName: { text: 'name', value: 'id' },
      quoteFile: [],
      quoteUploadFile: [],
      remark: '',
      activeName: ['0']
    })

    onMounted(() => {
      getRelevanceClueList()
      getQuoteSubjectInfo()
      getProductListInfo()
      state.userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (state.userInfo) {
        state.linkman = state.userInfo.realName
        state.linkmanPhone = state.userInfo.phone
        state.linkmanEmail = state.userInfo.email
      }

      state.quoteDate = formatterDateHourMinute(new Date())
      if (route.query.businessId) {
        state.businessQuoteId = route.query.businessId
        getBusinessDetailInfo()
      }
    })

    const getRelevanceClueList = () => {
      let params = {
        current: 1,
        size: 10000
      }
      getRelevanceClue(params).then((res) => {
        state.clueColumns = res.records
      })
    }

    const getBusinessDetailInfo = () => {
      getBusinessDetail({ id: state.businessQuoteId }).then((res) => {
        console.log('........', res)
        state.relevanceClue.id = res.id
        state.relevanceClue.sn = res.sn
        state.quoteTitle = res.title + '报价单'
        state.quoteSubject.name = res.ownerCompanyName
        state.quoteSubject.id = res.ownerCompanyId
        state.linkman = res.ownerUser
        state.linkmanPhone = res.ownerPhoneNumber
        state.linkmanEmail = res.ownerEmail
        state.inquirer = res.customerName
        state.inquirerLinkman = res.contactsName
        state.inquirerLinkmanPhone = res.phoneNumber
        state.inquirerLinkmanEmail = res.email
        if (res?.enclosureList?.length) {
          res.enclosureList.forEach((item) => {
            state.quoteFile.push({
              url: item.value
            })
          })
          state.quoteUploadFile = res.enclosureList
        }
        state.remark = res.remark

        // state.productItems = res // 产品明细未赋值
      })
    }

    const getQuoteSubjectInfo = () => {
      getQuoteSubject().then((res) => {
        state.quoteSubjectColumns = res
      })
    }

    const getProductListInfo = () => {
      let params = {
        productStatus: 'UP',
        name: state.businessSearchkey,
        current: 1,
        size: 10000
      }
      getProductList(params).then((res) => {
        state.businessModalColumns = res.records
      })
    }
    const onSearch = () => {
      getProductListInfo()
    }

    const onConfirmClue = (value) => {
      if (value) {
        state.relevanceClue = value
      }

      if (value.ownerUser) {
        state.linkman = value.ownerUser
      }
      if (value.ownerPhoneNumber) {
        state.linkmanPhone = value.ownerPhoneNumber
      }
      if (value.customerName) {
        state.inquirer = value.customerName
      }
      if (value.contactsName) {
        state.inquirerLinkman = value.contactsName
      }
      if (value.phoneNumber) {
        state.inquirerLinkmanPhone = value.phoneNumber
      }
      if (value.email) {
        state.inquirerLinkmanEmail = value.email
      }
      state.showCluePicker = false
    }

    const onConfirmQuoteDate = (value) => {
      console.log('//////', value)
      state.quoteDate = formatterDateHourMinute(value)
      state.showQuoteDatePicker = false
    }

    const onConfirmQuoteSubject = (value) => {
      console.log(';;;;;;', value)
      if(value) {
        state.quoteSubject = value
        console.log('quoteSubject:::', state.quoteSubject)
      }
      state.showQuoteSubjectPicker = false
    }

    const handleAddProduct = (index) => {
      console.log('.....', index)
      if (state.productItems[index].id) {
        state.productItems.push({
          productName: '', //产品名称
          productSn: '', //产品sn
          productId: '', //产品id
          categoryId: '',
          categoryName: '',
          coverImageList: [], //产品封面
          fitMachine: '', //产品配置参数
          isNewProduct: '', //产品成色
          price: '', //产品月租
          quantity: '', // 产品数量
          amount: '', //产品小计
          blackFreeQuantity: '', //产品黑白免印数
          blackAdvancePrice: '', //产品黑白超张价
          colorFreeQuantity: '', //产品彩色免印量
          colorAdvancePrice: '', //产品彩色超张价
          remark: ''
        })
      } else {
        Toast('请先选择产品！')
      }
      console.log('==========', state.productItems)
    }

    const handleDeleteProduct = (index) => {
      state.productItems.splice(index, 1)
    }

    const chooseBusinessModal = (index) => {
      console.log(index)
      state.businiessProductId = state.productItems[state.chooseModalCurrent].id
      state.businessSearchkey = ''
      state.chooseModalCurrent = index
      state.showBusinessModalPicker = true
      getProductListInfo()
    }

    const onConfirmBusinessModal = (val) => {
      console.log('val', val)
      console.log('index', state.chooseModalCurrent)
      if (val) {
        const value = state.businessModalColumns.filter((i) => {
          return i.id == val
        })[0]
        nextTick(() => {
          state.productItems[state.chooseModalCurrent] = {
            ...value,
            productName: value.name, //产品名称
            productSn: value.sn, //产品sn
            productId: value.id, //产品id
            coverImageList: [
              {
                url: value.coverImage
              }
            ],
            quantity: 1,
            amount: Number(value.price)
          }
          // state.productItems[index].businessModal = value
          
          console.log('productItems:::', state.productItems)
        })
      }
      state.showBusinessModalPicker = false
    }

    const inputQuantity = (item, index) => {
      if (item.id) {
        state.productItems[index].amount = Number(item.quantity) * item.price
      }
    }

    const afterRead = (file) => {
      // 此时可以自行将文件上传至服务器
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file)
      console.log('formData:::', formData)
      // 示例使用 axios 进行文件上传
      uploadFile(formData)
    }

    const uploadFile = (formData) => {
      // 使用你的上传接口地址替换以下 URL
      const url = 'web-service/oss/endpoint/put-file'
      // 这里使用 axios 作为请求示例
      request
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            // 这里可以获取上传进度
            console.log(progressEvent)
          }
        })
        .then((response) => {
          // 上传成功处理
          state.quoteUploadFile.push({
            label: response.originalName,
            value: response.link
          })
        })
        .catch((error) => {
          // 上传失败处理
          console.error(error)
        })
    }

    const onSubmit = (orderStatus) => {
      addQuoteForm.value
        .validate()
        .then(() => {
					let quantityCount = 0
					if(state.productItems.length) {
						state.productItems.forEach(item => {
							quantityCount += Number(item.quantity || 0)
						})
					}
					console.log("quantityCount;:::", quantityCount)
	       
          const productItems = state.productItems.filter((item) => item.id)

          if (!productItems.length) {
            return Toast.fail('请选择产品！')
          } else {
            state.productItems = productItems
          }
          let params = {
            // id: state.businessQuoteId,
            businessId: state.relevanceClue.id,
            businessSn: state.relevanceClue.sn,
            title: state.quoteTitle,
            quotationDate: state.quoteDate,
            ownerCompanyName: state.quoteSubject.name,
            ownerCompanyId: state.quoteSubject.id,
            ownerUser: state.linkman,
            ownerPhoneNumber: state.linkmanPhone,
            ownerEmail: state.linkmanEmail,
            ownerUserId: state.userInfo.id,
            // ownerUser: realName,
            ownerDeptId: state.userInfo.deptId,
            ownerDeptName: state.userInfo.deptName,
            // ownerPhoneNumber: phone,
            customerName: state.inquirer,
            contactsName: state.inquirerLinkman,
            phoneNumber: state.inquirerLinkmanPhone,
            email: state.inquirerLinkmanEmail,
            productItems: state.productItems,
	          // quantity: state.productItems.length,
	          quantity: quantityCount,
            orderStatus: orderStatus, // 报价状态
            enclosureList: state.quoteUploadFile, // 附件
            remark: state.remark // 报价备注
          }
          console.log('提交', params)
          addBusinessQuotation(params).then((res) => {
            console.log('res;:::', res)
            Toast.success(`${orderStatus === 'YBJ' ? '新建并发送' : '新建'}报价成功！`)
            setTimeout(() => {
              router.back()
            }, 500)
          })
        })
        .catch((error) => {
          console.log('.....', error)
        })
    }

    return {
      addQuoteForm,
      ...toRefs(state),
      onSubmit,
      onConfirmClue,
      onConfirmQuoteDate,
      onConfirmQuoteSubject,
      handleAddProduct,
      handleDeleteProduct,
      chooseBusinessModal,
      onConfirmBusinessModal,
      inputQuantity,
      onSearch,
      formatter,
      afterRead
    }
  }
}
</script>

<style scoped lang="less">
.addVisiting-container {
  padding-bottom: 90px;

  .addVisiting-save {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }

  .bottom-operation {
    display: flex;
    align-items: center;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    width: 100%;
    height: 80px;
  }
}
</style>
